package blq.ssnb.redbagaide.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import blq.ssnb.redbagaide.R;
import blq.ssnb.redbagaide.service.RedBagService;

import static android.preference.PreferenceActivity.EXTRA_NO_HEADERS;
import static android.preference.PreferenceActivity.EXTRA_SHOW_FRAGMENT;
import static android.preference.PreferenceActivity.EXTRA_SHOW_FRAGMENT_TITLE;

public class MainActivity extends Activity {
    private static String TAG = MainActivity.class.getSimpleName();
    private TextView aideStatusView;
    private TextView toAideBtn;
    private boolean isServerOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aideStatusView = findViewById(R.id.tv_aide_status_view);
        toAideBtn = findViewById(R.id.tv_to_aide);
        toAideBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toAideSetting();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshView();
        cancelNotification();
    }

    private void refreshView() {
        if (isAccessibilitySettingsOn(this)) {
            aideStatusView.setText("开");
            isServerOpen = true;
        } else {
            aideStatusView.setText("关");
            isServerOpen = false;
        }
    }

    private void toAideSetting() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        startActivity(intent);
    }

    private boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        // TestService为对应的服务
        final String service = getPackageName() + "/" + RedBagService.class.getCanonicalName();
        Log.i(TAG, "service:" + service);
        // com.z.buildingaccessibilityservices/android.accessibilityservice.AccessibilityService
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
            Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "Error finding setting, default accessibility to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            // com.z.buildingaccessibilityservices/com.z.buildingaccessibilityservices.TestService
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
        }
        return false;
    }

    @Override
    protected void onStop() {
        if (isServerOpen) {
            newNotification();
        }
        super.onStop();
    }

    private void newNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("read_bg","ssnb",NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "10001");
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setChannelId("read_bg")
                .setContentTitle("红包助手")
                .setContentText("正在运行")
                .setOngoing(true)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        notificationManager.notify(10020, builder.build());
    }

    private void cancelNotification() {
        ((NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(10020);
    }
}
